/*******************************************************************************
 * @project: fant-old
 * @package: com.acconsys.ant.tasks
 * @file: VersionTask.java
 * @author: bruce
 * @created: 2010-11-4
 * @purpose:
 * 
 * @version: 1.0
 * 
 * Revision History at the end of file.
 * 
 * Copyright 2010 AcconSys All rights reserved.
 ******************************************************************************/

package com.acconsys.ant.tasks;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

public class VersionTask extends Task {
	private String version;
	private String table;
	private String sequence;
	private String fileName;
	
	@Override
	public void init() throws BuildException {
		super.init();
		setTaskName("fant.version");
	}
	
	@Override
	public void execute() throws BuildException {
		if(version == null || version.trim().length() <= 0){
			throw new BuildException("必须提供版本号version");
		}
		if(fileName == null || fileName.trim().length() <= 0){
			fileName = "version.sql";
		}
		if(table == null || table.trim().length() <= 0){
			table = "version";
		}

		try {
			OutputStreamWriter out = new OutputStreamWriter(
					new FileOutputStream(fileName), "UTF-8");
			
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String lineSeperator = System.getProperty("line.separator");
			StringBuilder time = new StringBuilder("-- Generate Time: ");
			time.append(dateFormat.format(new Date()));
			time.append(lineSeperator);
			time.append("insert into ");
			time.append(table);
			if(sequence != null && sequence.trim().length() > 0){
				time.append(" values(");
				time.append(sequence);
				time.append(".nextVal");
				time.append(", '");
				time.append(version);
				time.append("');");
			}else{
				time.append("(version) values('");
				time.append(version);
				time.append("');");
			}
			out.write(time.toString());
			out.flush();
			out.close();

			log("[fant:version] " + fileName);
		} catch (Exception e) {
			throw new BuildException(e.getMessage());
		}
	}

	public void setVersion(String version) {
		this.version = version;
	}

	public void setTable(String table) {
		this.table = table;
	}

	public void setSequence(String sequence) {
		this.sequence = sequence;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
}



/*******************************************************************************
 * <B>Revision History</B><BR>
 * [type 'revision' and press Alt + / to insert revision block]<BR>
 * 
 * 
 * 
 * Copyright 2010 AcconSys All rights reserved.
 ******************************************************************************/